package com.cqc.manage.service.Imp.business;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqc.manage.dto.AmountBusinessDto;
import com.cqc.manage.entity.CostStatistics;
import com.cqc.manage.entity.Equipment;
import com.cqc.manage.mapper.CostStatisticsMapper;
import com.cqc.manage.repositories.CostStatisticsRepositories;
import com.cqc.manage.util.BaseValue;
import com.cqc.manage.util.thrift.TTSocket;
import com.cqc.manage.util.thrift.ThriftClientConnectPoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Configuration
@EnableScheduling
@Component
public class CostStatisticsService {


    private Logger LOG = LoggerFactory.getLogger(CostStatisticsService.class);

    @Autowired
    private CostStatisticsRepositories costStatisticsRepositories;

    @Autowired
    private ThriftClientConnectPoolFactory thriftClientConnectPoolFactory;

    @Autowired
    private BusinessEchartService businessEchartService;

    @Autowired
    private CostStatisticsMapper costStatisticsMapper;


    /**
     * 定时任务，每晚12点同步  costStatistics数据同步
     */
    @Scheduled(cron = "0 0 21 * * ?")
    public void saveData(){
        for (String engname : BaseValue.getEngName()){
            TTSocket ttSocket = null;
            try {
                ttSocket = thriftClientConnectPoolFactory.getConnect();
                List<Map<String, String>> costStatistics = ttSocket.getService().getCostStatistics(engname);
                List<String> allContractNo = costStatisticsRepositories.getAllContractNo(engname);
                for (Map<String,String> map:costStatistics){
                    LOG.info("{}",map);
                    if (allContractNo.contains(map.get("合同编号"))){
                        try{
                            CostStatistics contractNo = costStatisticsRepositories.findByConstartNo(map.get("合同编号"));
                            setData(map,contractNo);
                            costStatisticsRepositories.save(contractNo);
                        }catch (Exception e){
                            System.err.println("CostStatisticsService 定时任务，每晚12点同步: "+map.get("合同编号"));
//                        e.printStackTrace();
                        }
                    }else {
                        CostStatistics costStatistics1 = new CostStatistics();
                        LOG.info("新业务：{}",map.get("合同编号"));
                        setData(map, costStatistics1);
                        costStatisticsRepositories.save(costStatistics1);
                    }
                }
                thriftClientConnectPoolFactory.returnConnection(ttSocket);
//                MailUtil.send("1054117754@qq.com", "同步成功", "costStatistics数据同步", false);
            }catch (Exception e){
                e.printStackTrace();
                costStatisticsRepositories.deleteByEngeer(engname);
                if (ttSocket!=null){
                    thriftClientConnectPoolFactory.invalidateObject(ttSocket);
                }
//                MailUtil.send("1054117754@qq.com", e.getMessage(), "costStatistics数据同步", false);
            }
        }
    }

    @CacheEvict(cacheNames = "echart-main" , key = "#str")
    public void removeEchartMainCache(String str){
        businessEchartService.getMainEchart(str);
    }


    public void setData(Map<String, String> map,CostStatistics costStatistics1){
        costStatistics1.setInvoiceAmount(map.get("发票金额"));
        costStatistics1.setInvoiceNumber(map.get("发票编号"));
        costStatistics1.setClient(map.get("委托单位"));
        costStatistics1.setAgreementAmount(map.get("协议金额"));
        costStatistics1.setAmountReceived(map.get("到帐分配金额"));
        costStatistics1.setConstartNo(map.get("合同编号"));
        costStatistics1.setEngeer(map.get("工程师"));
        costStatistics1.setId(UUID.randomUUID().toString().replace("-","")+new Date().toString());
        costStatistics1.setStatus(map.get("状态"));
        costStatistics1.setInvoiceAllocationAmount(map.get("发票分配金额"));
        costStatistics1.setInvoiceDate(map.get("开票日期") == "" ? DateUtil.parse(map.get("开票日期"),"yyyy-MM-dd"): null);
        costStatistics1.setInvoiceDistributionDepartment(map.get("发票分配部门"));
        costStatistics1.setReportType(map.get("报告类型"));
        costStatistics1.setNature(map.get("检验性质"));
        costStatistics1.setPayer(map.get("付款单位"));
        costStatistics1.setReportNumber(map.get("报告编号"));
        costStatistics1.setAmountReceiveDate(map.get("到帐日期") == "" ? DateUtil.parse(map.get("到帐日期"),"yyyy-MM-dd"):null);
        costStatistics1.setApplicationNumber(map.get("申请编号"));
        costStatistics1.setStartDate(getStartDate(map.get("合同编号")));
    }

    public String getStartDate(String str){
        String substring = str.substring(1, 5);
        String substring1 = str.substring(5, 7);
        String substring2 = str.substring(7, 9);
        return substring+"-"+substring1+"-"+substring2;
    }

    /**
     * 每个工程师的业务情况
     */
    public float getEngineerAmount(String name,String startDate,String endDate){
        Float sum = 0.0F;
        if (endDate == null && startDate == null){
            List<CostStatistics> byEngeer = costStatisticsRepositories.findByEngeer(name);
            for (CostStatistics costStatistics:byEngeer){
                if (!costStatistics.getAmountReceived().equals("")) {
                    sum +=Float.valueOf(costStatistics.getAmountReceived());
                }

            }
        }else{
            Date date_start = DateUtil.parse(startDate);
            Date date_end = DateUtil.parse(endDate);
            List<CostStatistics> byEngeer = costStatisticsRepositories.findByEngeer(name);
            for (CostStatistics costStatistics:byEngeer){
                Date date = DateUtil.parse(costStatistics.getStartDate());
                if ( (DateUtil.year(date) >= DateUtil.year(date_start)) && (DateUtil.year(date) <= DateUtil.year(date_end))){
                    if ((DateUtil.month(date)+1 >= DateUtil.month(date_start)+1) && (DateUtil.month(date)+1 <= DateUtil.month(date_end)+1)){
                        if (!costStatistics.getAmountReceived().equals("")) {
                            sum +=Float.valueOf(costStatistics.getAmountReceived());
                        }
                    }
                }
            }
        }


        return sum;
    }

    public Map<String,Float> getAllEngineerAmount(){

        Map<String,Float> map = new HashMap<>();

        map.put("程敏",getEngineerAmount("程敏",null,null));
        map.put("杨琨",getEngineerAmount("杨琨",null,null));

        return map;

    }

    /**
     * 获取工程师的协议金额和发票金额
     */
    public AmountBusinessDto getEngineerCost(){
        List<Float> amountReceivedList = new ArrayList<>();
        List<Float> agreementAmountList = new ArrayList<>();
        List<String> engineerList = new ArrayList<>();
//        engineerList.add("程安");
//        engineerList.add("佟雨停");
//        engineerList.add("郝斌");
//        engineerList.add("刘凯");
//        engineerList.add("陆培光");
        engineerList.add("董银生");
        engineerList.add("王发娟");
        engineerList.add("黄雨吉");
        engineerList.add("江魏佳");
        engineerList.add("胡舜杰");
        engineerList.add("汪洋");
        engineerList.add("翁良汉");
        engineerList.add("杨琨");
        engineerList.add("杨远礼");
        engineerList.add("程敏");
        for (String engName:engineerList) {
            Float sum_AmountReceived = 0.0f;
            Float sum_AgreementAmount = 0.0f;
            List<CostStatistics> byEngeer = costStatisticsRepositories.findByEngeer(engName);
            for (CostStatistics costStatistics:byEngeer){
                int year = DateUtil.year(new Date());
                if ( DateUtil.year(DateUtil.parse(costStatistics.getStartDate())) == year ){
                    if (!costStatistics.getAmountReceived().equals("")){
                        sum_AmountReceived+= Float.valueOf(costStatistics.getAmountReceived());
                    }
                    if (!costStatistics.getAgreementAmount().equals("")){
                        sum_AgreementAmount += Float.valueOf(costStatistics.getAgreementAmount());
                    }
                }
            }
            amountReceivedList.add(sum_AmountReceived);
            agreementAmountList.add(sum_AgreementAmount);
        }
        AmountBusinessDto amountBusinessDto = new AmountBusinessDto();
        amountBusinessDto.setEngName(engineerList);
        amountBusinessDto.setAgreementAmountLit(agreementAmountList);
        amountBusinessDto.setAmountReceivedList(amountReceivedList);

        float all = 0.0F;
        for (Float f: agreementAmountList ) {
            all+=f;
        }
        amountBusinessDto.setAgreementAmount(all+"");
        all = 0.0F;
        for (Float f : amountReceivedList){
            all += f;
        }
        amountBusinessDto.setAmountReceived(all+"");
        return amountBusinessDto;
    }


    /**
     * echarts第三个饼图，统计每个公司在我们公司的做的业务
     */
    public List<Map<String, Integer>> getPieCompanyStatistics(){
        List<Map<String, Integer>> stringIntegerMap = costStatisticsMapper.selectCompanyAgreementAmount();
        LOG.info(stringIntegerMap.toString());
        return stringIntegerMap;
    }





}
